import { color } from 'cc';
import { Vec4 } from 'cc';
import { v4 } from 'cc';
import { director, Node, Scene, Color, v3, Vec3 } from 'cc';

const _v30 = v3();
const _color0 = color();

export namespace ColorTools {

    export function colorToV4(_color: Color | string, _map?: (_color: Color) => void) {
        if (typeof (_color) == 'string') {
            _color = color().fromHEX(_color);
        }
        _color0.set(_color);
        if (_map != null) _map(_color0);
        return v4(_color0.r / 255, _color0.g / 255, _color0.b / 255, _color0.a / 255);
    }

    export function colorSRGBV4(_color: Color | string) {
        if (typeof (_color) == 'string') {
            _color = color().fromHEX(_color);
        }
        let _v40 = v4(_color.r / 255, _color.g / 255, _color.b / 255, _color.a / 255);
        linearToSRGB(_v40);
        return _v40;
    }

    export function colorLinearV4(_color: Color | string) {
        if (typeof (_color) == 'string') {
            _color = color().fromHEX(_color);
        }
        let _v40 = v4(_color.r / 255, _color.g / 255, _color.b / 255, _color.a / 255);
        console.log('>>before linear', JSON.stringify(_v40));
        srgbToLinear(_v40);
        console.log('>>after linear', JSON.stringify(_v40));
        return _v40;
    }

    function linearToSRGB(linear: Vec4) {
        function convert(color) {
            if (color <= 0.0031308) {
                return 12.92 * color;
            } else {
                return 1.055 * Math.pow(color, 1 / 2.4) - 0.055;
            }
        }

        const r = convert(linear.x);
        const g = convert(linear.y);
        const b = convert(linear.z);

        linear.x = r;
        linear.y = g;
        linear.z = b;
    }

    function srgbToLinear(srgb: Vec4) {
        function convert(color) {
            if (color <= 0.04045) {
                return color / 12.92;
            } else {
                return Math.pow((color + 0.055) / 1.055, 2.4);
            }
        }

        const r = convert(srgb.x);
        const g = convert(srgb.y);
        const b = convert(srgb.z);

        srgb.x = r;
        srgb.y = g;
        srgb.z = b;
    }
}

globalThis.ColorTools = ColorTools;